/**
 * 
 */
package com.star.http;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.SerializableEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;

/**
 * @ClassName: HttpToolkit
 * @Description: 用来和仁济的webservice交互
 * @author starhq
 * @createtime 2014年7月30日 下午10:18:27
 * @email : jian.wang@shinsoft.net
 * @modify by TODO
 * @resaon
 * @edittime
 * @version 1.0
 * @copyright shinsoft
 */
public class HttpToolkit {

	private static final CloseableHttpClient httpClient;
	public static final String CHARSET = "UTF-8";

	static {
		RequestConfig config = RequestConfig.custom().setConnectTimeout(60000)
				.setSocketTimeout(15000).build();
		httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config)
				.build();
	}

	public static String doPost(String url, Serializable serialObject) {
		return doPost(url, serialObject, CHARSET);
	}

	public static String doPost(String url, Serializable serialObject,
			String charset) {
		if (!StringUtils.hasText(url)) {
			return null;
		}
		HttpPost post = new HttpPost(url);

		try {
			post.setEntity(new SerializableEntity(serialObject, false));
			CloseableHttpResponse response = httpClient.execute(post);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				post.abort();
				throw new RuntimeException("HttpClient,error status code :"
						+ statusCode);
			}
			HttpEntity entity = response.getEntity();
			String result = null;
			if (entity != null) {
				result = EntityUtils.toString(entity, "utf-8");
			}
			EntityUtils.consume(entity);
			response.close();
			return result;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			post.releaseConnection();
		}
		return null;
	}

	public static String doGet(String url, Map<String, String> params) {
		return doGet(url, params, CHARSET);
	}

	public static String doGet(String url, Map<String, String> params,
			String charset) {
		if (!StringUtils.hasText(url)) {
			return null;
		}
		try {
			if (params != null && !params.isEmpty()) {
				List<NameValuePair> pairs = new ArrayList<NameValuePair>(
						params.size());
				for (Map.Entry<String, String> entry : params.entrySet()) {
					String value = entry.getValue();
					if (value != null) {
						pairs.add(new BasicNameValuePair(entry.getKey(), value));
					}
				}
				url += "?"
						+ EntityUtils.toString(new UrlEncodedFormEntity(pairs,
								charset));
			}
			HttpGet httpGet = new HttpGet(url);
			CloseableHttpResponse response = httpClient.execute(httpGet);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				httpGet.abort();
				throw new RuntimeException("HttpClient,error status code :"
						+ statusCode);
			}
			HttpEntity entity = response.getEntity();
			String result = null;
			if (entity != null) {
				result = EntityUtils.toString(entity, "utf-8");
			}
			EntityUtils.consume(entity);
			response.close();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String doPost(String url, Map<String, String> params,
			String charset) {
		if (!StringUtils.hasText(url)) {
			return null;
		}
		try {
			List<NameValuePair> pairs = null;
			if (params != null && !params.isEmpty()) {
				pairs = new ArrayList<NameValuePair>(params.size());
				for (Map.Entry<String, String> entry : params.entrySet()) {
					String value = entry.getValue();
					if (value != null) {
						pairs.add(new BasicNameValuePair(entry.getKey(), value));
					}
				}
			}
			HttpPost httpPost = new HttpPost(url);
			if (pairs != null && pairs.size() > 0) {
				httpPost.setEntity(new UrlEncodedFormEntity(pairs, charset));
			}
			CloseableHttpResponse response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				httpPost.abort();
				throw new RuntimeException("HttpClient,error status code :"
						+ statusCode);
			}
			HttpEntity entity = response.getEntity();
			String result = null;
			if (entity != null) {
				result = EntityUtils.toString(entity, "UTF-8");
			}
			EntityUtils.consume(entity);
			response.close();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String doPost(String url, Map<String, String> params) {
		return doPost(url, params, CHARSET);
	}

	public static String doPost(String url, String json, String charset) {
		if (!StringUtils.hasText(url)) {
			return null;
		}
		HttpPost post = new HttpPost(url);

		try {
			post.addHeader("Content-type", "application/json");
			post.setEntity(new StringEntity(json, charset));
			CloseableHttpResponse response = httpClient.execute(post);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				post.abort();
				throw new RuntimeException("HttpClient,error status code :"
						+ statusCode);
			}
			HttpEntity entity = response.getEntity();
			String result = null;
			if (entity != null) {
				result = EntityUtils.toString(entity, "utf-8");
			}
			EntityUtils.consume(entity);
			response.close();
			return result;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			post.releaseConnection();
		}
		return null;
	}

	public static String doPost(String url, String json) {
		return doPost(url, json, CHARSET);
	}

	public static void main(String[] args) {
		// ============servlet测试开始====================
		// RequestModel model = new RequestModel();
		// model.setType("0");
		// model.setIdNo("310112198802224349");
		// model.setIdType("1");

		// model.setType("2");
		// model.setIdNo("321283198805103626");
		// model.setIdType("1");
		// model.setPatientName("翁长碗");

		// model.setType("3");
		// model.setIdNo("321283198805103626");
		// model.setIdType("1");
		// model.setPatientName("翁长碗");
		// model.setPatientId("268351");
		// model.setSex("F");
		// model.setBirthDay("1988-05-10");
		// model.setPhoneNo1("15921874332");
		// model.setRegnDate("2014-08-21");
		// model.setTimeRange("001");
		// model.setRegId("FCK102");
		// model.setWaitingQueueNo("1");
		// model.setBookingTime("2014-08-21 08:00:00");

		// model.setType("4");
		// model.setPatientId("268351");
		// model.setPatientName("翁长碗");
		// model.setSex("F");
		// model.setBirthDay("1988-05-10");
		// model.setIdNo("321283198805103626");
		// model.setIdType("1");
		// model.setPhoneNo("15921874332");
		// model.setRegnDate("2014-08-21");
		// model.setTimeRange("001");
		// model.setRegId("FCK102");
		// model.setTimesLotId("001");
		// model.setWaitingQueueNo("1");
		// model.setBookingNo("42477");

		// model.setType("5");
		// model.setPatientId("268351");
		// model.setVisitNo("830447");
		// model.setRequestNo("1675253");
		// model.setReportNo("1516035");

		// model.setType("6");
		// model.setPatientId("268351");
		// model.setVisitNo("4");
		// model.setRequestNo("8");

		// model.setType("7");
		// model.setPatientId("268351");
		// model.setRequestDatetimeFrom("2014-05-19 16:53:00");
		// model.setRequestDatetimeTo("2014-08-30 23:59:59");

		// model.setType("8");
		// model.setPatientId("268351");
		// model.setVisitNo("2");
		// model.setRequestNo("2");
		// model.setReportNo("15");

		// model.setType("9");
		// model.setPatientId("8");
		// model.setVisitNo("3");
		// model.setRequestNo("10");

		// model.setType("10");
		// model.setPatientId("268351");
		// model.setRequestDatetimeFrom("2014-05-19 16:53:00");
		// model.setRequestDatetimeTo("2014-08-30 23:59:59");

		// model.setType("11");
		// model.setRegId("FCK104");
		// model.setRegnDateFrom("2014-09-03");

		// model.setType("21");
		// model.setRegId("FCK104");

		// model.setType("12");
		// model.setRegId("FCK104");

		// model.setType("13");
		// model.setPatientId("277538");
		// model.setPreId("2014-10-2");
		// model.setMdate("2014-08-04");
		// model.setPweeks(100);
		// model.setPday(20);
		// model.setPcount(100);
		// model.setBph(10.0f);
		// model.setBpl(5.0f);
		// model.setWeight(60.0f);
		// model.setMtype(0);
		// model.setBglucose(10.0f);
		// model.setDuration("");

		// model.setType("14");
		// model.setPatientId("277538");

		// http://180.166.62.50:8007/RENJIServlet
		// System.out.println(doPost("http://180.166.62.50:8007/RENJIServlet",
		// model));

		// String result = doPost("http://180.166.62.50:8007/RENJIServlet",
		// model);

		// XStreamUtils.getXMLToList(result, "Items", "Item",
		// QueryPatientInfoListBO.class);
		// System.out.println("hello");

		// ============servlet测试结束====================

		// ===============hospital测试开始====================
		// JSONObject value = new JSONObject();

		// value.put("jym", "R009");
		// value.put("regId", "FCK102");

		// value.put("jym", "R005");
		// value.put("hospitalName", "1");

		// value.put("jym", "R006");
		// value.put("hospitalName", "1");
		// value.put("regId", "0025");

		// 仁济
		// value.put("jym", "R007");
		// value.put("hospitalName", "0");
		// value.put("regId", "FCK102");
		// value.put("regnDate", "2014-09-12");
		// value.put("patientName", "王燕");
		// value.put("sex", "F");
		// value.put("birthDay", "1985/1/14 0:00:00");
		// value.put("idNo", "310226198512192629");
		// value.put("idType", "1");
		// value.put("phoneNo1", "13024144112");

		// pfy
		// value.put("jym", "R007");
		// value.put("hospitalName", "1");
		// value.put("regId", "0025");
		// value.put("regnDate", "2014-08-25");
		// value.put("patientName", "殷懿萍");
		// value.put("phoneNo2", "张琳");
		// value.put("idNo", "321283198805103626");
		// value.put("idType", "1");

		// value.put("jym", "R008");
		// value.put("hospitalname", "0");
		// value.put("oid", "43d88e5b-d56e-4e87-b3f9-258144f0b150");

		// value.put("jym", "R016");
		// value.put("hospitalName", "0");
		// value.put("idNo", "310107198501140925");
		// value.put("idType", "1");

		// value.put("jym", "R000");
		// value.put("hospitalName", "1");
		// value.put("idType", "1");
		// value.put("idNo", "310107198605090942");

		// value.put("jym", "R002");
		// value.put("idType", "1");
		// value.put("idNo", "310101198808250020");
		// value.put("patientName", "潘颖颖");

		// value.put("jym", "R004");
		// value.put(
		// "data",
		// "{'age':'30','birthDatetime':'1982-04-23','expectedDate':'2014/10/18 0:00:00','idNo':'1234567890','idType':'1','jym':'R003','lastMDate':'2014/1/1 0:00:00','patientName':'starhq','phoneNo':'13817057728','preId':'2014-8-1','residence':'上海闵行','sex':'F'}");

		// value.put("jym", "R005");
		// value.put("hospitalName", "0");

		// value.put("jym", "R006");
		// value.put("hospitalName", "1");
		// value.put("regId", "0025");

		// value.put("jym", "R010");
		// value.put("patientId", "268351");
		// value.put("visitNo", "830447");
		// value.put("requestNo", "1675233");
		// value.put("reportNo", "1587099");

		// value.put("jym", "R011");
		// value.put("patientId", "268351");
		// value.put("visitNo", "830447");
		// value.put("requestNo", "1675235");

		// value.put("jym", "R012");
		// value.put("patientId", "268351");
		// value.put("idNo", "321283198805103626");
		// value.put("idType", "1");

		// value.put("jym", "R013");
		// value.put("patientId", "268351	");
		// value.put("visitNo", "1587099");
		// value.put("requestNo", "1675233");
		// value.put("reportNo", "830447");

		// value.put("jym", "R014");
		// value.put("patientId", "268351");
		// value.put("visitNo", "830447");
		// value.put("requestNo", "1675235");

		// value.put("jym", "R015");
		// value.put("patientId", "305867");
		// value.put("idNo", "620103198509275020");
		// value.put("idType", "1");

		// Map<String, String> params = new HashMap<String, String>(1);
		// params.put("JsonData", value.toString());

		// System.out.println(doPost(
		// "http://m.e-medicine.cn:8080/Hospital/RenJiService", params));

		// System.out.println(doPost(
		// "http://localhost:8080/Hospital/RenJiService", params));

		// ===============hospital测试结束====================

		// =================health测试开始===========================
		// Map<String, String> params1 = new HashMap<String, String>();

		// params1.put("type", "0");
		// params1.put("userId", "${@print(md5(this_is_a_test_string))}");
		// params1.put("page", "1");
		// params1.put("limit", "1");

		// 血糖
		// params1.put("userId", "${@print(md5(this_is_a_test_string))}");
		// params1.put("patientId", "0000");
		// params1.put("preId", "0000-00-00");
		// params1.put("type", "0");
		// params1.put("measureDate",
		// new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
		// params1.put("measureValueFasting", "10.0");

		// 血压
		// params1.put("userId", "82270a5e-61f1-413d-9ca5-ebf3ccc6bb75");
		// params1.put("type", "1");
		// params1.put("patientId", "0000");
		// params1.put("preId", "0000-00-00");
		// params1.put("measureDate",
		// new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
		// params1.put("measureValueH", "20.0");
		// params1.put("measureValueL", "10.0");

		// 体重
		// params1.put("userId", "82270a5e-61f1-413d-9ca5-ebf3ccc6bb75");
		// params1.put("type", "2");
		// params1.put("patientId", "0000");
		// params1.put("preId", "0000-00-00");
		// params1.put("measureDate",
		// new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
		// params1.put("measureValue", "20.0");

		// 胎动
		// params1.put("userId", "82270a5e-61f1-413d-9ca5-ebf3ccc6bb75");
		// params1.put("type", "3");
		// params1.put("patientId", "0000");
		// params1.put("preId", "0000-00-00");
		// params1.put("measureDate",
		// new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		// params1.put("measureValue", "20.0");
		// params1.put("measureStart", "06:00:00");
		// params1.put("measureEnd", "09:00:00");
		// params1.put("quickeningCount", "39");
		// params1.put("pweeks", "2");
		// params1.put("pday", "10");

		// System.out.println(doGet(
		// "http://m.e-medicine.cn:8080/Hospital/HealthService/get", params1));

		// =================health测试结束===========================

		// Map<String, String> params = new HashMap<String, String>();

		// 发卡
		// params.put("roomId", "5c6dc30d-1b7c-4a2d-af77-8e12b4b94596");
		// params.put("cardNum", "30ac15734015188c");
		// params.put("cardNum", "12345");
		// params.put("address", "上海上海市徐汇区桂平路22207");
		// params.put("id", "e54f97b9-1e27-4825-b1b8-d2a5b865fa96");
		// // params.put("type", "1");
		// params.put("type", "3");
		// params.put("gatewayId", "11111111");
		// params.put("lockId", "02");
		// params.put("start", "2010-01-01 00:01");
		// params.put("end", "2019-12-31 23:59");
		// params.put("name", "starhq");
		// System.out.println(doPost("http://localhost:8082/Room/cm", params));

		// 删除发卡
		// params.put("id", "ea410243-feba-4680-9880-d863178e7e67");
		// params.put("roomId", "5c6dc30d-1b7c-4a2d-af77-8e12b4b94596");
		// params.put("serial", "01");
		// params.put("type", "1");
		// params.put("username", "starhq");
		// System.out.println(doPost("http://localhost:8082/Room/cm/deleteCM",
		// params));

		// 查询发卡
		// params.put("id", "5c6dc30d-1b7c-4a2d-af77-8e12b4b94596");
		// System.out.println(doGet("http://localhost:8082/Room/cm", params));

		// 查询字典
		// params.put("id", "310104");
		// System.out.println(doGet("http://localhost:8082/Room/d/4", params));

		// 保存字典
		// params.put("id", "d14fefe9-d20e-4452-8398-39cdc904d51f");
		// System.out
		// .println(doGet("http://localhost:8082/Room/d/delete", params));

		// 查询电量
		// System.out.println(doGet("http://localhost:8082/Room/e", params));

		// 设置时间
		// params.put("roomId", "5c6dc30d-1b7c-4a2d-af77-8e12b4b94596");
		// params.put("username", "starhq");
		// System.out
		// .println(doGet("http://localhost:8082/Room/c/readTime", params));

		// Map<String, String> maps = new HashMap<String, String>(1);
		// maps.put("id", "d602734a-b2d3-4f14-912a-e6193983887f");
		// maps.put("name", "红旗小区");
		// System.out.println(doPost("http://localhost:8080/JDGZF/n/dictionary",
		// maps));

		Map<String, String> maps = new HashMap<String, String>(2);
		maps.put("province", "上海");
		maps.put("city", "上海市");
		maps.put("district", "徐汇区");
		maps.put("street", "创业中心大厦");
		maps.put("buildingNum", "33");
		maps.put("floors", "");
		// maps.put("roomNum", "10");
		maps.put("type", "三居室");
		System.out.println(doPost("http://localhost:8080/Room/r", maps));
	}
}
